#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>

ssize_t	writen(int fd, const void *vptr, size_t n);
void handle_signal(int s);
void InitSignal(void);


ssize_t	
writen(int fd, const void *vptr, size_t n)
{
	size_t		nleft;
	ssize_t		nwritten;
	const char	*ptr;

	ptr = vptr;
	nleft = n;
	while (nleft > 0) {
		if ( (nwritten = write(fd, ptr, nleft)) <= 0) {
			if (errno == EINTR)
				nwritten = 0;		/* and call write() again */
			else
				return(-1);			/* error */
		}

		nleft -= nwritten;
		ptr   += nwritten;
	}
	return(n);
}

void 
handle_signal(int s) 
{ 
    //printf("%d,broken pipe!!!!\n", s);
    //usleep(1000);
    InitSignal();
}

void 
InitSignal(void)
{
    //printf("init singal\n");
    signal(SIGPIPE,handle_signal);
}


/* do nothing with the signal and reset the signal option */


int
main(int argc, char **argv)
{
	int					sockfd, n;
	struct sockaddr_in	servaddr;
	char				recvline[200];
	
	long i = 0;
	int flags;
	
	char http_request[] = ""
"GET / HTTP/1.1\r\n"
"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml\r\n"
"Referer: http://www.163.com/\r\n"
"Accept-Language: zh-cn\r\n"
"\r\n"
;

    InitSignal();
    
	for (;;){
	
	    sockfd = socket(AF_INET, SOCK_STREAM, 0);

        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family      = AF_INET;
        servaddr.sin_addr.s_addr = inet_addr("10.210.158.105");
        servaddr.sin_port        = htons(80);	/* daytime server */
	    
	    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
	    {
		    //printf("connect error\n");
		    close(sockfd);
		    //usleep(10);
		    continue;
        }
    
        writen(sockfd, http_request, sizeof(http_request));

	    //usleep(1);
	
	    while ((n = read(sockfd, recvline, 1)) > 0) {
			usleep(10);
			printf("%.*s\n", n, recvline);
		}

        i++;
        
        if (i % 1000 == 0)
        {
            printf("%d\n", i);
        }
        
        sleep(99999);
		
		
		/*
		if ( i == 50000)
			break;
        }
        */
        close(sockfd);
	}

	exit(0);
}
